//
//  FriendSystemMessageTb.m
//  project
//
//  Created by 黄建华 on 2018/8/9.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "FriendSystemMessageTb.h"
#import "SystemTableViewCell.h"

@implementation FriendSystemMessageTb

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _tableView                              = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.width, self.height) style:UITableViewStylePlain];
        _tableView.delegate                     = self;
        _tableView.dataSource                   = self;
        _tableView.separatorStyle               = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        [self addSubview:_tableView];
        _maxPage     = 1;
        _currentPage = 1;
        [self createMjHeader];
        [self createMjFooter];
    }
    return self;
}

- (void)loadFooterData {
    if (_currentPage < _maxPage) {
        _currentPage++;
        [self getMessage];
        [self endRefreshing:3.0 withTypte:2];
    } else {
        [self endRefreshing:0.5 withTypte:2];
        SHOWMBProgressHUD(SN_Text(@"已经到底了"), nil, nil, NO, 2.0);
    }
    NSLog(@"下拉刷新>>>>>>");
}

- (void)endRefreshing:(CGFloat)time withTypte:(NSInteger)type {
    __unsafe_unretained UITableView *tableView = self.tableView;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 结束刷新
        if (type == 1) {
            [tableView.mj_header endRefreshing];
        }
        else
        {
            [tableView.mj_footer endRefreshing];
        }
    });
}

// 上拉刷新
- (void)createMjFooter {
    _footer                            = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadFooterData)];
    _footer.backgroundColor            = SNCOLORGRAYLINE;
    _footer.alpha                      = 0.5;
    _footer.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
    [_footer setTitle:SN_Text(@"点击或者上拉加载更多") forState:MJRefreshStateIdle];
    [_footer setTitle:SN_Text(@"松开刷新") forState:MJRefreshStatePulling];
    [_footer setTitle:SN_Text(@"加载 ...") forState:MJRefreshStateRefreshing];
    _footer.stateLabel.font                       = [UIFont systemFontOfSize:15];
    _footer.stateLabel.textColor                  = SNCOLORGRAY;
    _tableView.mj_footer                          = _footer;
    _tableView.mj_footer.automaticallyChangeAlpha = YES;
    _tableView.mj_footer                          = _footer;
}

// 下拉刷新
- (void)createMjHeader
{
    _myHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadHeaderData)];
    _myHeader.backgroundColor            = [UIColor colorFromHex:0x4b4b4b];
    _myHeader.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
    // 设置文字
    [_myHeader setTitle:SN_Text(@"下拉刷新") forState:MJRefreshStateIdle];
    [_myHeader setTitle:SN_Text(@"松开刷新") forState:MJRefreshStatePulling];
    [_myHeader setTitle:SN_Text(@"加载 ...") forState:MJRefreshStateRefreshing];
    
    // 设置字体
    _myHeader.stateLabel.font           = [UIFont systemFontOfSize:15];
    _myHeader.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14];
    _myHeader.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@:%@", SN_Text(@"上次更新"), [[NSDate date]dateToString]];
    
    // 设置颜色
    _myHeader.stateLabel.textColor           = SNCOLORGRAY;
    _myHeader.lastUpdatedTimeLabel.textColor = SNCOLORGRAY;
    // 设置刷新控件
    _tableView.mj_header                          = _myHeader;
    _tableView.mj_header.automaticallyChangeAlpha = YES;
}

- (void)loadHeaderData {
    NSLog(@"下拉刷新>>>>>>>>");
    [self updateFriendRequest];
    [self endRefreshing:3.0 withTypte:1];
}

- (void)updateFriendRequest {
    _currentPage = 1;
    [self getMessage];
}

- (void)updateUIViewWith:(NSDictionary *)dic
{
//    NSLog(@"更新系统消息>>>>>%@",dic);
    if (dic) {
        NSArray *items = dic[@"items"];
        if (items.count == 0) {
            _currentPage = 1;
            _maxPage = 1;
            _tableView.mj_footer.hidden = YES;
        } else {
            NSDictionary *metaDic = dic[@"_meta"];
            _currentPage = [metaDic[@"currentPage"]integerValue];
            _maxPage = [metaDic[@"pageCount"]integerValue];
            
            if (_maxPage == 1 || (_currentPage == _maxPage)) {
                _tableView.mj_footer.hidden = YES;
            } else {
                _tableView.mj_footer.hidden = NO;
            }
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *dicItem in items) {
                NSDictionary *sendUserDic = dicItem[@"sender"];
                FriednInviterModel *model = [[FriednInviterModel alloc] init];
                model.userId = [sendUserDic[@"id"]integerValue];
                model.nickName = sendUserDic[@"nickname"];
                model.gender = [sendUserDic[@"gender"]integerValue];
                NSString *getTime = dicItem[@"send_time"];
                NSDate *startTime = [NSDate dateByString:getTime];
                NSDate *date = startTime; // 获得时间对象
                NSTimeZone *zone = [NSTimeZone systemTimeZone]; // 获得系统的时区
                NSTimeInterval time = [zone secondsFromGMTForDate:date];// 以秒为单位返回当前时间与系统格林尼治时间的差
                NSDate *dateNow = [date dateByAddingTimeInterval:+time];// 然后把差的时间加
                NSString *sendTime = [dateNow dateToString];
                model.send_time = sendTime;
                model.imagePathUrlString = sendUserDic[@"portrait"];
                model.content = dicItem[@"content"];
                NSString *type = dicItem[@"type"];
                model.type = @"3";
                if ([type isEqualToString:@"encourage"]) {
                    model.type = @"1";
                }
                if ([type isEqualToString:@"thumb"]) {
                    model.type = @"2";
                }
                [array addObject:model];
            }
            
            _dataArray = [NSMutableArray arrayWithArray:array];
            [_tableView reloadData];
//            1:显示用户消息列表  2:已读当前页请求
        }
    }
}

- (void)getMessage
{
    DEF_WEAKSELF_(FriendSystemMessageTb)
    [SN_Net friendGetSystemWithPage:_currentPage Success:^(id object) {
        NSDictionary *dic = object;
        if (dic) {
            [weakSelf updateUIViewWith:dic];
        }
    } fail:^(id object) {
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString     *identifier = @"systemmessageTableViewCell";
    SystemTableViewCell *cell       = [tableView cellForRowAtIndexPath:indexPath];
    
    if (nil == cell) {
        cell = [[SystemTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    
    FriednInviterModel *model = _dataArray[indexPath.row];
    [cell updateCellWithModel:model];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSLog(@"系统消息请求选择了>>>%d", indexPath.row);
    FriednInviterModel *model = _dataArray[indexPath.row];
    if (_selectBlock) {
        _selectBlock(model);
    }
}

@end
